package com.du.springmvc.controller;

import com.du.springmvc.bean.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Locale;

/**
 * @author : DuJiabao
 * @Project : spring-mvc
 * @Time : 2021/4/2 16:39
 * @Desc :
 */
@Controller
public class ConverterController {
  @RequestMapping("/stringToEmployeeTest")
  public String stringToEmployeeTest(@RequestParam("employee") Manager employee) {
    System.out.println(employee);
    return "success";
  }

  @RequestMapping("/stringToEnumTest")
  public String stringToEnumTest(@RequestParam("gender") Gender gender) {
    System.out.println(gender);
    return "success";
  }

  @RequestMapping("/formatTest")
  public String formatTest(Person person) {
    System.out.println(person);
    return "success";
  }

  @RequestMapping("/validationTest")
  public String validationTest(@Valid People people, BindingResult bindingResult) {
    System.out.println(people);
    if (bindingResult.hasErrors()) {
      System.out.println("发生错误");
      return "forward:validation.jsp";
    }
    return "success";
  }

  @ResponseBody
  @RequestMapping("/jsonTest")
  public Collection<Employee> jsonTest() {
    ArrayList<Employee> employees = new ArrayList<>();
    employees.add(new Employee(0, "jack", Gender.male));
    employees.add(new Employee(1, "john", Gender.male));
    employees.add(new Employee(2, "lucy", Gender.female));
    return employees;
  }

  @RequestMapping("/getJsonTest")
  public String getJsonTest(@RequestBody Employee employee) {
    System.out.println(employee);
    return "success";
  }

  @RequestMapping("/requestBodyTest")
  public String requestBodyTest(@RequestBody String requestBody) {
    System.out.println(requestBody); // {"id":0,"name":"john","gender":"male"}
    return "success";
  }

  @RequestMapping("/httpEntityTest")
  public ResponseEntity<String> httpEntityTest(HttpEntity<String> httpEntity) {
    System.out.println(httpEntity);
    HttpHeaders headers = httpEntity.getHeaders(); // [host:"localhost:8080", connection:"keep-alive", content-length:"38", accept:"*/*", origin:"http://localhost:8080", x-requested-with:"XMLHttpRequest", user-agent:"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3861.400 QQBrowser/10.7.4313.400", referer:"http://localhost:8080/databinder/sendJson.jsp", accept-encoding:"gzip, deflate, br", accept-language:"zh-CN,zh;q=0.9", cookie:"JSESSIONID=39099CC91B33EAED591D26A1CD87732A", Content-Type:"application/json;charset=UTF-8"]
    System.out.println(headers);

    String body = httpEntity.getBody();  // {"id":0,"name":"john","gender":"male"}
    System.out.println(body);

    HttpHeaders responseHeaders = new HttpHeaders();
    responseHeaders.add("Content-Type", "application/json");
    return new ResponseEntity<>(body, responseHeaders, HttpStatus.OK);
  }

  @RequestMapping("/download")
  public ResponseEntity<byte[]> download(HttpServletRequest request) throws Exception {
    // 设置响应头
    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.set("Content-Disposition", "attachment;filename=jquery-1.7.2.js");
    // 读取文件流
    InputStream inputStream = request.getServletContext().getResourceAsStream("script/jquery-1.7.2.js");
    byte[] bytes = new byte[inputStream.available()];
    if (inputStream.read(bytes) > 0) System.out.println("文件读取成功");
    // 返回响应整体
    return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
  }

  @RequestMapping("/upload")
  public String upload(@RequestParam("uploadFile") MultipartFile uploadFile) throws IOException {
    if (!uploadFile.isEmpty()) {
      uploadFile.transferTo(Paths.get("E:/" + uploadFile.getOriginalFilename()));
    }
    return "success";
  }

  @RequestMapping("/upload2")
  public String upload2(@RequestParam("uploadFiles") MultipartFile[] uploadFiles, String name) throws IOException {
    System.out.println(name);
    for (MultipartFile uploadFile : uploadFiles) {
      if (!uploadFile.isEmpty()) {
        System.out.println(uploadFile.getOriginalFilename());
        uploadFile.transferTo(Paths.get("E:/" + uploadFile.getOriginalFilename()));
      }
    }
    System.out.println("处理成功");
    return "success";
  }

  @RequestMapping("/intercepted")
  public String intercepted() {
    System.out.println("intercepted方法执行");
    return "intercepted";
  }

  @RequestMapping("/login2")
  public String login2(HttpServletRequest request, HttpSession httpSession) {
    String localeStr = request.getParameter("locale");
    Locale locale = null;
    if (localeStr == null || "".equals(localeStr)) {
      locale =  request.getLocale();
    } else {
      String language = localeStr.split("_")[0];
      String country = localeStr.split("_")[1];
      locale =  new Locale(language, country);
    }
    httpSession.setAttribute(SessionLocaleResolver.class.getName() + ".LOCALE", locale);
    return "login2";
  }
}
